package com.smt.modules.bus.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.smt.common.enums.Code;
import com.smt.common.enums.StageEnum;
import com.smt.common.utils.Constant;
import com.smt.common.utils.EnumToKeyUtil;
import com.smt.common.utils.R;
import com.smt.modules.bus.dao.ProjectTaskDao;
import com.smt.modules.bus.entity.MemberUserEntity;
import com.smt.modules.bus.entity.SubtaskEntity;
import com.smt.modules.bus.entity.TeamEntity;
import com.smt.modules.bus.pojo.SituationPojo;
import com.smt.modules.bus.service.*;
import com.smt.modules.bus.vo.request.ConceptualReq;
import com.smt.modules.bus.entity.ProjectTaskEntity;
import com.smt.modules.bus.vo.request.SituationReq;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 阶段计划数据显示
 *
 * @author zhangyi
 * @date 2018/10/8 16:41
 */
@Service
public class ConceptualProgressServiceImpl extends ServiceImpl<ProjectTaskDao,ProjectTaskEntity> implements ConceptualProgressService {

    @Autowired
    private ProjectTaskService projectTaskService;

    @Autowired
    private TeamService teamService;

    @Autowired
    private SubtaskService subtaskService;

    @Autowired
    private MemberUserService memberUserService;

    /**
     * 获取阶段性进度
     *
     * @param conceptualReq
     * @return
     */
    @Override
    public R progresses(ConceptualReq conceptualReq, Long userId) {
        //获取当前项目下的各个阶段任务的进行情况 将没每个任务的完成和非完成情况输出
        Long projectId = conceptualReq.getProjectId();
        if(projectId == null){
            return R.error(EnumToKeyUtil.toInt(Code.APPEND_DATA_ERROR),"项目不存在");
        }

        //有效任务列表
        List<ProjectTaskEntity> projectTaskList = projectTaskService.selectList(new EntityWrapper<ProjectTaskEntity>()
                .eq("project_id", projectId)
                .in("status",Constant.SQL_CON));

        Collections.sort(projectTaskList,(x,y) ->{
            return x.getStageId().compareTo(y.getStageId());
        });
        List<List<ProjectTaskEntity>> taskLists = new ArrayList<>();

        for (int i = 1; i <= StageEnum.values().length;i++){
            int[] j = new int[]{i};
            List<ProjectTaskEntity> taskList = new ArrayList<>();
            projectTaskList.stream()
                    .forEach(p -> {
                        Integer stageId = p.getStageId();
                        if(stageId.equals(j[0])){
                            taskList.add(p);
                        }
                    });
            taskLists.add(taskList);
        }
        return R.ok().put("taskLists",taskLists);
    }

    /**
     * 任务状况
     *
     * @param situationReq
     * @return
     */
    @Override
    public R situation(SituationReq situationReq) {
        Map<String,Integer> situationMap = new HashMap<>();
        SituationPojo situationPojo = new SituationPojo();
        BeanUtils.copyProperties(situationReq,situationPojo);
        //所有项目任务列表
        List<ProjectTaskEntity> projectTaskEntities =
                baseMapper.situationLists(situationPojo);

        // 子任务列表
        List<SubtaskEntity> subTaskList = new LinkedList<>();
        //获取任务列表
        projectTaskEntities.stream().map(ProjectTaskEntity::getId)
                .forEach(id -> {
                    List<SubtaskEntity> subTasks = subtaskService.selectList(new EntityWrapper<SubtaskEntity>()
                            .eq("project_task_id", id)
                            .in("status",Constant.SQL_CON));
                    subTaskList.addAll(subTasks);
                });
        //获取总的任务数
        situationMap.put("all",projectTaskEntities.size());
        //将总任务书分成三部分（完成,未完成进行中,延期,项目责任人被删除100）
        Integer[] situationArray = new Integer[]{0,0,0};
        if(projectTaskEntities.size() != 0){
            projectTaskEntities.stream()
                    .forEach(e -> {
                        Long memberId = e.getMemberId();
                        if(null != memberId && memberId.equals(situationReq.getUserId())) {
                            setSituation(situationArray, e.getStatus());
                        }
                    });
            //任务下的子任务完成情况
            subTaskList.stream()
                    .forEach(s -> {
                        Long memberId = s.getMemberId();
                        if(memberId != null && memberId.equals(situationReq.getUserId())) {
                            setSituation(situationArray, s.getStatus());
                        }
                    });
            situationMap.put("working",situationArray[0]);
            situationMap.put("success",situationArray[1]);
            situationMap.put("extension",situationArray[2]);
        }
        return R.ok().put("map",situationMap);
    }

    /**
     * 获取该项目的所有成员
     *
     * @param projectId
     * @return
     */
    @Override
    public R memberLists(Long projectId) {
        List<TeamEntity> teamList = teamService.selectList(new EntityWrapper<TeamEntity>()
                .eq("project_id", projectId)
                .eq("member_exist",0));
        List<Map<String,Object>> listUser = new ArrayList<>();
        //获取成员列表
        teamList.stream().map(TeamEntity::getMemberId)
        .forEach(m -> {
                MemberUserEntity memberUserEntity = memberUserService.selectOne(new EntityWrapper<MemberUserEntity>()
                        .eq("user_id", m));
            String username = memberUserEntity.getUsername();
            String contact = Objects.isNull(memberUserEntity.getEmail()) ? memberUserEntity.getMobile() : memberUserEntity.getEmail();
            String userName = Objects.isNull(username) ? contact : username;
            Map<String, Object> map = new ConcurrentHashMap<>();
                map.put("memberId", m);
                map.put("userName", userName);
                listUser.add(map);
        });
        return R.ok().put("names",listUser);
    }

    /**
     * 对应每一种状态
     *
     * @param s
     * @param status
     * @return
     */
    private Integer[] setSituation(Integer s[],Integer status){
        if(status.equals(Constant.S_WORKING) ||
                status.equals(Constant.S_WORKING_50) ||
                status.equals(Constant.S_WORKING_401)){
            s[0] += 1;
        }else if(status.equals(Constant.S_SUCCESS)){
            s[1] += 1;
        }else if(status.equals(Constant.S_EXTENSION)){
            s[2] += 1;
        }
        return s;
    }
}
